template
<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { onMounted } from 'vue'
// 引入分类相关的API函数
import {
  addCategory,
  getCategoryById,
  getCategoryList,
  deleteCategory,
  updateCategory
} from '@/api/category.js'
import { ElMessage, ElMessageBox } from 'element-plus'

// 存储分类列表的数据
const categoryList = ref([])
// 获取分类数据
onMounted(async () => {
  await init()
})

/**
 * 初始化分类列表
 * 该函数在组件挂载时调用，用于获取分类数据
 */
const init = async () => {
  try {
    const response = await getCategoryList()
    if (response && response.data) {
      categoryList.value = response.data
    } else {
      categoryList.value = []
    }
    // eslint-disable-next-line no-unused-vars
  } catch (error) {
    ElMessage.error('获取初始分类数据失败')
  }
}

// 控制添加分类对话框的显示状态
const dialogvisible = ref(false)

// 添加分类的数据模型
const categoryModel = ref({
  categoryName: '',
  categoryAlias: '',
})

// 添加分类表单的验证规则
const rules = {
  categoryAlias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
  ],
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
  ],
}

/**
 * 提交添加分类表单
 * 收集表单数据并调用添加分类的API函数
 */
const addCategoryForm = async () => {
  try {
    let res = await addCategory(categoryModel.value)
    ElMessage.success(res.message ? res.message : '添加成功')
    await getCategoryList()
    await init()
    categoryModel.value = {}
    dialogvisible.value = false
    // eslint-disable-next-line no-unused-vars
  } catch (error) {
    ElMessage.error('添加分类失败，请稍后再试')
  }
}

// 控制修改分类对话框的显示状态
const updateVisible = ref(false)

/**
 * 打开修改分类对话框
 * 根据行数据获取分类信息并填充到表单中
 * @param {Object} row - 表格行数据
 */
const updateHandler = async row => {
  console.log(row)
  try {
    const response = await getCategoryById(row.id)
    if (response && response.data) {
      categoryModel.value = response.data
      updateVisible.value = true
    } else {
      ElMessage.error('获取分类信息失败')
    }
    // eslint-disable-next-line no-unused-vars
  } catch (error) {
    ElMessage.error('获取分类信息失败')
  }
}

/**
 * 提交修改分类表单
 * 收集表单数据并调用修改分类的API函数
 */
const updateFormSubmit = async () => {
  try {
    let res = await updateCategory(categoryModel.value)
    init()
    categoryModel.value = {}
    ElMessage.success(res.message ? res.message : '修改成功')
    updateVisible.value = false
    // eslint-disable-next-line no-unused-vars
  } catch (error) {
    ElMessage.error('修改分类失败，请稍后再试')
  }
}

/**
 * 处理删除分类操作
 * 弹出确认对话框并调用删除分类的API函数
 * @param {Number} id - 分类ID
 */
const deleteHandler = async id => {
  // 确认是否删除
  const confirm = await ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  if (confirm) {
    try {
      let res = await deleteCategory(id)
      ElMessage.success(res.message ? res.message : '删除成功')
      await init()
      // eslint-disable-next-line no-unused-vars
    } catch (error) {
      ElMessage.error('删除分类失败，请稍后再试')
    }
  }
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>课程分类</span>
        <div class="extra">
          <el-button type="primary" @click="dialogvisible = true"
          >添加分类
          </el-button>
        </div>
      </div>
    </template>
    <el-table :data="categoryList" style="width: 100%">
      <el-table-column label="序号" width="100" type="index"></el-table-column>
      <el-table-column label="分类名称" prop="categoryName"></el-table-column>
      <el-table-column label="分类别名" prop="categoryAlias"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            @click="updateHandler(scope.row)"
          ></el-button>
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click="deleteHandler(scope.row.id)"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <el-dialog v-model="dialogvisible" title="添加分类" width="30%">
      <el-form
        :model="categoryModel"
        :rules="rules"
        label-width="100px"
        style="padding-right: 30px"
      >
        <el-form-item label="分类名称" prop="categoryName">
          <el-input
            v-model="categoryModel.categoryName"
            minlength="1"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类别名" prop="categoryAlias">
          <el-input
            v-model="categoryModel.categoryAlias"
            minlength="1"
            maxlength="15"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogvisible = false">取消</el-button>
          <el-button type="primary" @click="addCategoryForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="updateVisible" title="修改分类" width="30%">
      <el-form
        :model="categoryModel"
        :rules="rules"
        label-width="100px"
        style="padding-right: 30px"
      >
        <el-form-item label="分类名称" prop="categoryName">
          <el-input
            v-model="categoryModel.categoryName"
            minlength="1"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类别名" prop="categoryAlias">
          <el-input
            v-model="categoryModel.categoryAlias"
            minlength="1"
            maxlength="15"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateVisible = false">取消</el-button>
          <el-button type="primary" @click="updateFormSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>

